package cn.com.cis.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class FileUtils {

	public static boolean writesString2File(String res, File distFile) {
		boolean flag = true;
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter = null;
		try {
			bufferedReader = new BufferedReader(new StringReader(res));
			bufferedWriter = new BufferedWriter(new FileWriter(distFile));
			char buf[] = new char[1024];
			int len;
			while ((len = bufferedReader.read(buf)) != -1) {
				bufferedWriter.write(buf, 0, len);
			}
			bufferedWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
			flag = false;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					flag = false;
					e.printStackTrace();
				}
			}
			
			if (bufferedWriter != null) {
				try {
					bufferedWriter.close();
				} catch (IOException e) {
					flag = false;
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
	
	public static String getDriverFolder(HttpServletRequest request) {
		String webAppRoot = request.getSession().getServletContext().getRealPath("/");
        String driversFolder = webAppRoot + "/drivers/";
        
        return driversFolder;
	}
	
	public static List<String> getDriverJars(HttpServletRequest request){
        List<String> jarFiles = new ArrayList<String>();
        for(String jarFileName : new File(getDriverFolder(request)).list()){
        	if (jarFileName.endsWith(".jar")) {
        		jarFiles.add(jarFileName);
			}
        }
        
        return jarFiles;
    }
}